<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;

    }

    /**
     * 地区树
     *
     */
    public function areaList()
    {
        $regions = db('goods')
            ->field([
                'SUBSTRING_INDEX(`city`, "/", 1) AS province',
                'SUBSTRING_INDEX(SUBSTRING_INDEX(`city`, "/", 2), "/", -1) AS city'
            ])
            ->group('province, city')
            ->select();
        $result = [];
        foreach ($regions as $v) {
            if (empty($result[$v['province']])) {
                $result[$v['province']] = [
                    'province' => $v['province'],
                    'city' => [],
                ];
            }
            if ($v['city']) {
                $result[$v['province']]['city'][] = $v['city'];
            }
        }
        $this->success('返回成功', $result);
    }


    /**
     * 列表
     *
     */
    public function list()
    {
        $page = $this->request->post("page/d",1);
        $pageSize = $this->request->post("pageSize/d",10);
        $regions = $this->request->post("regions/s");
        $sort = $this->request->post("sort/s",'weigh');
        $order = $this->request->post("order/s",'desc');
        $where = [
            'goods.status' => 3,
        ];
        !empty($regions) && $where['goods.city'] = ['like','%'.$regions.'%'],
        $total = $this->model
            ->with('group')
            ->where($where)
            ->count();
        $totalPages = max(ceil($total / $pageSize),1);
        $page = max(min($page, $totalPages),1);
        $list = $this->model
            ->with('group')
            ->where($where)
            ->order($sort, $order)
            ->page($page, $pageSize)
            ->select();
        $this->success('返回成功', [
            'list'       => $list,
            'total'      => $total,
            'page'       => $page,
            'pageSize'   => $pageSize,
            'totalPages' => $totalPages,
        ]);
    }


    /**
     * 详情
     *
     */
    public function detail()
    {
        $id = $this->request->post("id");
        $goods = $this->model
            ->with('group')
            ->where([
                'id'     => $id,
                'status' => 3,
            ])
            ->find();
        $orderCount = db('order')
            ->where([
                'goods_id' => $id,
                'status'   => 4,
            ])
            ->count();
        $this->success('返回成功', ['goods' => $goods,'orderCount' => $orderCount]);
    }

}
